<?php
namespace app\manage\controller;

use app\apple\model\EstateMeter;
use app\applet\model\ElectricityMeter;
use app\applet\model\GasMeter;
use app\applet\model\NetMeter;
use app\applet\model\WaterMeter;
use app\manage\model\AdminUser;
use app\manage\model\ElectricityBill;
use app\manage\model\EstateBill;
use app\manage\model\GasBill;
use app\manage\model\NetBill;
use app\manage\model\WaterBill;
use think\Controller;
use think\Request;
use \app\manage\model\ApartmentSettings;
use app\manage\model\Shops;
use app\manage\model\HousingInformation;
use app\manage\model\ContracTmanagement;
use \app\manage\model\TenantManagement;

class ApartmentCost extends Controller {
    public function __construct(Request $request = null)
    {
//        parent::__construct($request);
    }

    /**
     * 公寓费用列表-水电气网物业
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function ListMeter() {
        $type = input()['type'];//电费、水费、气费、网费、物业费
        $status = input()['status'];//缴费状态，未缴、已缴、补缴
        $page = input()['page'];
        $admin_id = input()['admin_id'];
        $time = input()['time'];// 1表示本月，2表示上月，3表示最近3个月
        $tung = input()['tung_num'];
        $unit = input()['unit_num'];
        $room_number = input()['room_number'];
        $model = new AdminUser();
        $admin_id = $model->findPlatId($admin_id);

        switch ($type) {
            case 1:
                $this->ListElectricity($admin_id, $status, $tung, $unit, $room_number, $page, $time);
                break;
            case 2:
                $this->ListWater($admin_id, $status, $tung, $unit, $room_number, $page, $time);
                break;
            case 3:
                $this->ListGas($admin_id, $status, $tung, $unit, $room_number, $page, $time);
                break;
            case 4:
                $this->ListNet($admin_id, $status, $tung, $unit, $room_number, $page, $time);
                break;
            case 5:
                $this->ListEstate($admin_id, $status, $tung, $unit, $room_number, $page, $time);
                break;
            default:
        }

    }

    /**
     * @param $admin_id
     * @param $electricity_fee
     * @param $status
     * @param $keyword
     * @param $page
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function ListElectricity($admin_id, $status, $tung, $unit, $room_number, $page, $time) {
        $model = new ElectricityBill();
        $list = $model->getList($admin_id, $status, $tung, $unit, $room_number, $page, $time);
        foreach ($list['data'] as $k => &$a) {
            $a['room_number'] = $a['tung_num'] . '-' . $a['unit_num'] . '-' . $a['room_number'];
            unset($a['tung_num']);
            unset($a['unit_num']);
            unset($a['layer_num']);
        }
        returnJson(200,'成功', $list)->send();
    }

    /**
     * @param $admin_id
     * @param $water_fee
     * @param $status
     * @param $keyword
     * @param $page
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function ListWater($admin_id, $status, $tung, $unit, $room_number, $page, $time) {
        $model = new WaterBill();
        $list = $model->getList($admin_id, $status, $tung, $unit, $room_number, $page, $time);
        foreach ($list['data'] as $k => &$a) {
            $a['room_number'] = $a['tung_num'] . '-' . $a['unit_num'] . '-' . $a['room_number'];
            unset($a['tung_num']);
            unset($a['unit_num']);
            unset($a['layer_num']);
        }
        returnJson(200,'成功', $list)->send();
    }

    /**
     * @param $admin_id
     * @param $gas_fee
     * @param $status
     * @param $keyword
     * @param $page
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function ListGas($admin_id, $status, $tung, $unit, $room_number, $page, $time) {
        $model = new GasBill();
        $list = $model->getList($admin_id, $status, $tung, $unit, $room_number, $page, $time);
        foreach ($list['data'] as $k => &$a) {
            $a['room_number'] = $a['tung_num'] . '-' . $a['unit_num'] . '-' . $a['room_number'];
            unset($a['tung_num']);
            unset($a['unit_num']);
            unset($a['layer_num']);
        }
        returnJson(200,'成功', $list)->send();
    }

    /**
     * @param $admin_id
     * @param $net_fee
     * @param $status
     * @param $keyword
     * @param $page
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function ListNet($admin_id, $status, $tung, $unit, $room_number, $page, $time) {
        $model = new NetBill();
        $list = $model->getList($admin_id, $status, $tung, $unit, $room_number, $page, $time);
        foreach ($list['data'] as $k => &$a) {
            $a['room_number'] = $a['tung_num'] . '-' . $a['unit_num'] . '-' . $a['room_number'];
            unset($a['tung_num']);
            unset($a['unit_num']);
            unset($a['layer_num']);
        }
        returnJson(200,'成功', $list)->send();
    }

    /**
     * @param $admin_id
     * @param $estate_fee
     * @param $status
     * @param $keyword
     * @param $page
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function ListEstate($admin_id, $status, $tung, $unit, $room_number, $page, $time) {
        $model = new EstateBill();
        $list = $model->getList($admin_id, $status, $tung, $unit, $room_number, $page, $time);
        foreach ($list['data'] as $k => &$a) {
            $a['room_number'] = $a['tung_num'] . '-' . $a['unit_num'] . '-' . $a['room_number'];
            unset($a['tung_num']);
            unset($a['unit_num']);
            unset($a['layer_num']);
        }
        returnJson(200,'成功', $list)->send();
    }

    /**
     * @param $house_id
     * @param $type
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function getTenantInfo($house_id, $type, $time) {
        if ($type == 1) {
            $model = new HousingInformation();
            $detail = $model->housingOne($house_id);
        } else {
            $model = new Shops();
            $detail = $model->shopsOne($house_id);
        }

        if ($detail['lease'] == 1) {
//        if (false) {
            return ['tenant_name'=>'', 'tel'=>''];// 未出租
        } else {//已出租
            /**
             * 1、去房屋合同关联表查询房屋id对应的最新合同id
             * 2、根据合同表查找租客id
             * 3、根据租客id查找租客信息
             */
            $model = new ContracTmanagement();
            $detail = $model->housingInformation($type, $house_id);
            $contract_id = $detail['c_c_mid'];

            $detail = $model->contractIdAllTenant($contract_id);
            $tenant_id = $detail['t_id'];

            $model = new TenantManagement();
            $detail = $model->tenantOne($tenant_id);
            return ['tenant_name'=>$detail['tenant_name'], 'tel'=>$detail['tenant_tel']];
        }
    }

    /**
     * 每月生成账单
     */
    public function generateBill() {
        $model = new AdminUser();
        $plat_list = $model->m_list(1);
        foreach ($plat_list as $plat) {
            $model = new ApartmentSettings();
            $set = $model->index2($plat['admin_id']);
            if ($set == null) continue;
            if ($set['settlement_time'] != date('d', time())) continue;
            $this->generateElectricityBill($plat['admin_id']);
            $this->generateWaterBill($plat['admin_id']);
            $this->generateGasBill($plat['admin_id']);
            $this->generateNetBill($plat['admin_id']);
            $this->generateEstateBill($plat['admin_id']);
        }

    }

    /**
     * 生成电费账单
     */
    private function generateElectricityBill($admin_id) {
        $model = new ElectricityMeter();
        $notCount = $model->getNotCount($admin_id);//获得未被统计过的抄表记录
        if (!empty($notCount)) {// 有记录且必须大于1，方可计算已使用量
            $house_info = [];
            // 制造每个房源账单信息
            foreach ($notCount as $house) {
                $room_number = $house['tung_num'] . '-' . $house['unit_num'] . '-' . $house['layer_num'] . '-' . $house['room_number'];
                if (!key_exists($room_number, $house_info)) {
                    $house_info[$room_number] = [];
                    $house_info[$room_number]['tenant_id'] = $house['tenant_id'];
                    $house_info[$room_number]['tenant_name'] = $house['tenant_name'];
                    $house_info[$room_number]['tenant_tel'] = $house['tenant_tel'];
                }
                // 账单基本信息
                $house_info[$room_number]['admin_id'] = $house['admin_id'];
                $house_info[$room_number]['number'] = $this->getNumber('D');
                $house_info[$room_number]['tung_num'] = $house['tung_num'];
                $house_info[$room_number]['unit_num'] = $house['unit_num'];
                $house_info[$room_number]['layer_num'] = $house['layer_num'];
                $house_info[$room_number]['room_number'] = $house['room_number'];
                $house_info[$room_number]['house_id'] = $house['house_id'];
                $house_info[$room_number]['type'] = $house['type'];

                // 统计最早时间和最晚时间、最早度数和最晚度数
                //首次将第一条记录作为其开始时间
                if (!isset($house_info[$room_number]['start_time'])) {
                    $a = $model->getLastRecord($house['house_id'], $house['type']);
                    if ($a === null) {
//                        $house_info[$room_number]['start_time'] = $house['time'];
//                        $house_info[$room_number]['start_number'] = $house['num'];
                        $house_info[$room_number]['start_time'] = 0;
                        $house_info[$room_number]['start_number'] = 0;
                    } else {
                        $house_info[$room_number]['start_time'] = $a['time'];
                        $house_info[$room_number]['start_number'] = $a['num'];
                    }
                }
                // 当前认为从数据库读出来的值越往后越新，故没有进行时间的判断
                $house_info[$room_number]['end_time'] = $house['time'];
                $house_info[$room_number]['end_number'] = $house['num'];

                // 统计费用
                $house_info[$room_number]['unit_price'] = $this->getElectricityUnit($house['admin_id']);//电费单价
                $house_info[$room_number]['time'] = '';
                $house_info[$room_number]['status'] = 1;

                // 账单基本信息
                $house_info[$room_number]['method'] = 1;
                $house_info[$room_number]['create_time'] = time();
            }

            // 计算总价
            foreach ($house_info as $k => &$item) {
                $item['usage'] = $item['end_number'] - $item['start_number'];
                $item['cost'] = upDecimal(bcmul($item['unit_price'] , $item['usage'], 6));
                if (empty($item['usage'])) {
                    unset($house_info[$k]);
                }
            }
            $house_info = array_merge_recursive($house_info);

            // 将每个房源账单信息插入账单表
            $model_bill = new ElectricityBill();
            foreach ($house_info as $h) {
                $model_bill->m_insert($h);
            }

            // 将抄表记录的统计状态更改为已统计
            $data['is_statistics'] = 1;
            foreach ($house_info as $house) {
                $a = $model->ListRoomNum($house['tung_num'], $house['unit_num'], $house['layer_num'], $house['room_number']);
                foreach ($a as $b) {
                    $model->m_update($b['id'], $data);
                }
            }
        }
    }

    /**
     * 生成水费账单
     */
    private function generateWaterBill($admin_id) {
        $model = new WaterMeter();
        $notCount = $model->getNotCount($admin_id);//获得未被统计过的抄表记录
        if (!empty($notCount)) {// 有记录且必须大于1，方可计算已使用量
            $house_info = [];
            // 制造每个房源账单信息
            foreach ($notCount as $house) {
                $room_number = $house['tung_num'] . '-' . $house['unit_num'] . '-' . $house['layer_num'] . '-' . $house['room_number'];
                if (!key_exists($room_number, $house_info)) {
                    $house_info[$room_number] = [];
                    $house_info[$room_number]['tenant_id'] = $house['tenant_id'];
                    $house_info[$room_number]['tenant_name'] = $house['tenant_name'];
                    $house_info[$room_number]['tenant_tel'] = $house['tenant_tel'];
                }
                // 账单基本信息
                $house_info[$room_number]['admin_id'] = $house['admin_id'];
                $house_info[$room_number]['number'] = $this->getNumber('S');
                $house_info[$room_number]['tung_num'] = $house['tung_num'];
                $house_info[$room_number]['unit_num'] = $house['unit_num'];
                $house_info[$room_number]['layer_num'] = $house['layer_num'];
                $house_info[$room_number]['room_number'] = $house['room_number'];
                $house_info[$room_number]['house_id'] = $house['house_id'];
                $house_info[$room_number]['type'] = $house['type'];

                // 统计最早时间和最晚时间、最早度数和最晚度数
                //首次将第一条记录作为其开始时间
                if (!isset($house_info[$room_number]['start_time'])) {
                    $a = $model->getLastRecord($house['house_id'], $house['type']);
                    if ($a === null) {
//                        $house_info[$room_number]['start_time'] = $house['time'];
//                        $house_info[$room_number]['start_number'] = $house['num'];
                        $house_info[$room_number]['start_time'] = 0;
                        $house_info[$room_number]['start_number'] = 0;
                    } else {
                        $house_info[$room_number]['start_time'] = $a['time'];
                        $house_info[$room_number]['start_number'] = $a['num'];
                    }
                }
                // 当前认为从数据库读出来的值越往后越新，故没有进行时间的判断
                $house_info[$room_number]['end_time'] = $house['time'];
                $house_info[$room_number]['end_number'] = $house['num'];

                // 统计费用
                $house_info[$room_number]['unit_price'] = $this->getWaterUnit($house['admin_id']);//电费单价
                $house_info[$room_number]['time'] = '';
                $house_info[$room_number]['status'] = 1;

                // 账单基本信息
                $house_info[$room_number]['method'] = 1;
                $house_info[$room_number]['create_time'] = time();
            }

            // 计算总价
            foreach ($house_info as $k => &$item) {
                $item['usage'] = $item['end_number'] - $item['start_number'];
                $item['cost'] = upDecimal(bcmul($item['unit_price'] , $item['usage'], 6));
                if (empty($item['usage'])) {
                    unset($house_info[$k]);
                }
            }
            $house_info = array_merge_recursive($house_info);

            // 将每个房源账单信息插入账单表
            $model_bill = new WaterBill();
            foreach ($house_info as $h) {
                $model_bill->m_insert($h);
            }

            // 将抄表记录的统计状态更改为已统计
            $data['is_statistics'] = 1;
            foreach ($house_info as $house) {
                $a = $model->ListRoomNum($house['tung_num'], $house['unit_num'], $house['layer_num'], $house['room_number']);
                foreach ($a as $b) {
                    $model->m_update($b['id'], $data);
                }
            }
        }
    }

    /**
     * 生成气费账单
     */
    private function generateGasBill($admin_id) {
        $model = new GasMeter();
        $notCount = $model->getNotCount($admin_id);//获得未被统计过的抄表记录
        if (!empty($notCount)) {// 有记录且必须大于1，方可计算已使用量
            $house_info = [];
            // 制造每个房源账单信息
            foreach ($notCount as $house) {
                $room_number = $house['tung_num'] . '-' . $house['unit_num'] . '-' . $house['layer_num'] . '-' . $house['room_number'];
                if (!key_exists($room_number, $house_info)) {
                    $house_info[$room_number] = [];
                    $house_info[$room_number]['tenant_id'] = $house['tenant_id'];
                    $house_info[$room_number]['tenant_name'] = $house['tenant_name'];
                    $house_info[$room_number]['tenant_tel'] = $house['tenant_tel'];
                }
                // 账单基本信息
                $house_info[$room_number]['admin_id'] = $house['admin_id'];
                $house_info[$room_number]['number'] = $this->getNumber('Q');
                $house_info[$room_number]['tung_num'] = $house['tung_num'];
                $house_info[$room_number]['unit_num'] = $house['unit_num'];
                $house_info[$room_number]['layer_num'] = $house['layer_num'];
                $house_info[$room_number]['room_number'] = $house['room_number'];
                $house_info[$room_number]['house_id'] = $house['house_id'];
                $house_info[$room_number]['type'] = $house['type'];

                // 统计最早时间和最晚时间、最早度数和最晚度数
                //首次将第一条记录作为其开始时间
                if (!isset($house_info[$room_number]['start_time'])) {
                    $a = $model->getLastRecord($house['house_id'], $house['type']);
                    if ($a === null) {
//                        $house_info[$room_number]['start_time'] = $house['time'];
//                        $house_info[$room_number]['start_number'] = $house['num'];
                        $house_info[$room_number]['start_time'] = 0;
                        $house_info[$room_number]['start_number'] = 0;
                    } else {
                        $house_info[$room_number]['start_time'] = $a['time'];
                        $house_info[$room_number]['start_number'] = $a['num'];
                    }
                }
                // 当前认为从数据库读出来的值越往后越新，故没有进行时间的判断
                $house_info[$room_number]['end_time'] = $house['time'];
                $house_info[$room_number]['end_number'] = $house['num'];

                // 统计费用
                $house_info[$room_number]['unit_price'] = $this->getGasUnit($house['admin_id']);//电费单价
                $house_info[$room_number]['time'] = '';
                $house_info[$room_number]['status'] = 1;

                // 账单基本信息
                $house_info[$room_number]['method'] = 1;
                $house_info[$room_number]['create_time'] = time();
            }

            // 计算总价
            foreach ($house_info as $k => &$item) {
                $item['usage'] = $item['end_number'] - $item['start_number'];
                $item['cost'] = upDecimal(bcmul($item['unit_price'] , $item['usage'], 6));
                if (empty($item['usage'])) {
                    unset($house_info[$k]);
                }
            }
            $house_info = array_merge_recursive($house_info);

            // 将每个房源账单信息插入账单表
            $model_bill = new GasBill();
            foreach ($house_info as $h) {
                $model_bill->m_insert($h);
            }

            // 将抄表记录的统计状态更改为已统计
            $data['is_statistics'] = 1;
            foreach ($house_info as $house) {
                $a = $model->ListRoomNum($house['tung_num'], $house['unit_num'], $house['layer_num'], $house['room_number']);
                foreach ($a as $b) {
                    $model->m_update($b['id'], $data);
                }
            }
        }
    }

    /**
     * 生成网费账单
     */
    private function generateNetBill($admin_id) {
        $model_house = new HousingInformation();
        $model_shop = new Shops();
        $model_contract = new ContracTmanagement();
        $data = [];

        $house_list = $model_house->indexLease($admin_id);
        foreach ($house_list as &$house) {
            $data['admin_id'] = $house['create_id'];
            $data['tung_num'] = $house['h_tung_num'];
            $data['unit_num'] = $house['h_unit_num'];
            $data['layer_num'] = $house['h_layer_num'];
            $data['room_number'] = $house['h_room_number'];
            $data['house_id'] = $house['housing_id'];
            $data['type'] = 1;
            $data['number'] = $this->getNumber('N');
            $data['create_time'] = time();
            $data['method'] = 1;
            $data['status'] = 1;

            $detail = $model_contract->contratHouse($house['housing_id'], 1);
            if (!isset($detail['c_c_mid'])) continue;
            $contract_id = $detail['c_c_mid'];

            $detail = $model_contract->ContractTenantInfo($contract_id);
            $data['tenant_id'] = $detail['tenant_id'];
            $data['tenant_name'] = $detail['tenant_name'];
            $data['tenant_tel'] = $detail['tenant_tel'];

            $detail = $model_contract->detail($contract_id);
            if (strtotime('-1 month') < $detail['c_a_time']) {// 签订合同时间不足一个月，起始时间用起实际时间
                $data['start_time'] = $detail['c_a_time'];
                $data['end_time'] = time();
                $data['usage'] = 1;//不满一月按一月计算
            } else {
                $data['start_time'] = strtotime('-1 month');
                $data['end_time'] = time();
                $data['usage'] = 1;
            }

            $data['unit_price'] = $this->getNetUnit($house['create_id']);//网费单价
            $data['cost'] = upDecimal(bcmul($data['unit_price'] , $data['usage'], 6));
            $model_bill = new NetBill();
            $model_bill->m_insert($data);
        }

        $shop_list = $model_shop->indexLease($admin_id);
        foreach ($shop_list as &$shop) {
            $data['admin_id'] = $shop['create_id'];
            $data['tung_num'] = $shop['s_tung_num'];
            $data['unit_num'] = $shop['s_unit_num'];
            $data['layer_num'] = $shop['s_layer_num'];
            $data['room_number'] = $shop['s_room_number'];
            $data['house_id'] = $shop['shops_id'];
            $data['type'] = 2;
            $data['number'] = $this->getNumber('N');
            $data['create_time'] = time();
            $data['method'] = 1;
            $data['status'] = 1;

            $detail = $model_contract->contratHouse($shop['shops_id'], 2);
            if (!isset($detail['c_c_mid'])) continue;
            $contract_id = $detail['c_c_mid'];

            $detail = $model_contract->ContractTenantInfo($contract_id);
            $data['tenant_id'] = $detail['tenant_id'];
            $data['tenant_name'] = $detail['tenant_name'];
            $data['tenant_tel'] = $detail['tenant_tel'];

            $detail = $model_contract->detail($contract_id);
            if (strtotime('-1 month') < $detail['c_a_time']) {// 签订合同时间不足一个月，起始时间用起实际时间
                $data['start_time'] = $detail['c_a_time'];
                $data['end_time'] = time();
                $data['usage'] = 1;
            } else {
                $data['start_time'] = strtotime('-1 month');
                $data['end_time'] = time();
                $data['usage'] = 1;
            }

            $data['unit_price'] = $this->getNetUnit($shop['create_id']);//电费单价
            $data['cost'] = upDecimal(bcmul($data['unit_price'] , $data['usage'], 6));

            $model_bill = new NetBill();
            $model_bill->m_insert($data);
        }
    }

    /**
     * 生成物业费账单
     */
    private function generateEstateBill($admin_id) {
        $model_house = new HousingInformation();
        $model_shop = new Shops();
        $model_contract = new ContracTmanagement();
        $data = [];

        $house_list = $model_house->indexLease($admin_id);
        foreach ($house_list as &$house) {
            $data['admin_id'] = $house['create_id'];
            $data['tung_num'] = $house['h_tung_num'];
            $data['unit_num'] = $house['h_unit_num'];
            $data['layer_num'] = $house['h_layer_num'];
            $data['room_number'] = $house['h_room_number'];
            $data['area'] = $house['h_area'];
            $data['house_id'] = $house['housing_id'];
            $data['type'] = 1;
            $data['number'] = $this->getNumber('W');
            $data['create_time'] = time();
            $data['method'] = 1;
            $data['status'] = 1;

            $detail = $model_contract->contratHouse($house['housing_id'], 1);
            if (!isset($detail['c_c_mid'])) continue;
            $contract_id = $detail['c_c_mid'];

            $detail = $model_contract->ContractTenantInfo($contract_id);
            $data['tenant_id'] = $detail['tenant_id'];
            $data['tenant_name'] = $detail['tenant_name'];
            $data['tenant_tel'] = $detail['tenant_tel'];

            $detail = $model_contract->detail($contract_id);
            if (strtotime('-1 month') < $detail['c_a_time']) {// 签订合同时间不足一个月
                $data['start_time'] = $detail['c_a_time'];
                $data['end_time'] = time();
                $data['usage'] = 1;
            } else {
                $data['start_time'] = strtotime('-1 month');
                $data['end_time'] = time();
                $data['usage'] = 1;
            }

            $data['unit_price'] = $this->getEstateUnit($house['create_id']);//电费单价
            $data['cost'] = upDecimal(bcmul(bcmul($data['unit_price'] , $data['usage'], 6), $data['area'], 6));

            $model_bill = new EstateBill();
            $model_bill->m_insert($data);
        }

        $shop_list = $model_shop->indexLease($admin_id);
        foreach ($shop_list as &$shop) {
            $data['admin_id'] = $shop['create_id'];
            $data['tung_num'] = $shop['s_tung_num'];
            $data['unit_num'] = $shop['s_unit_num'];
            $data['layer_num'] = $shop['s_layer_num'];
            $data['room_number'] = $shop['s_room_number'];
            $data['area'] = $shop['s_area'];
            $data['house_id'] = $shop['shops_id'];
            $data['type'] = 2;
            $data['number'] = $this->getNumber('W');
            $data['create_time'] = time();
            $data['method'] = 1;
            $data['status'] = 1;

            $detail = $model_contract->contratHouse($shop['shops_id'], 2);
            if (!isset($detail['c_c_mid'])) continue;
            $contract_id = $detail['c_c_mid'];

            $detail = $model_contract->ContractTenantInfo($contract_id);
            $data['tenant_id'] = $detail['tenant_id'];
            $data['tenant_name'] = $detail['tenant_name'];
            $data['tenant_tel'] = $detail['tenant_tel'];

            $detail = $model_contract->detail($contract_id);
            if (strtotime('-1 month') < $detail['c_a_time']) {// 签订合同时间不足一个月
                $data['start_time'] = $detail['c_a_time'];
                $data['end_time'] = time();
                $data['usage'] = 1;
            } else {
                $data['start_time'] = strtotime('-1 month');
                $data['end_time'] = time();
                $data['usage'] = 1;
            }

            $data['unit_price'] = $this->getEstateUnit($shop['create_id']);//电费单价
            $data['cost'] = upDecimal(bcmul(bcmul($data['unit_price'] , $data['usage'], 6) , $data['area'], 6));

            $model_bill = new EstateBill();
            $model_bill->m_insert($data);
        }
    }

    /**
     * 生成账单编号
     * @param $type string   D表示电费，S表示水费，Q表示气费，N表示网费，W表示物业
     * 还需验证生成账单时的编号是否唯一
     */
    public function getNumber($type) {
        static $hot_data = [];
        $prefix = 'GY';
        $figure = rand(10000000, 99999999);
        switch (strtoupper($type)) {
            case 'D':
                $model = new ElectricityBill();
                break;
            case 'S':
                $model = new WaterBill();
                break;
            case 'Q':
                $model = new GasBill();
                break;
            case 'N':
                $model = new NetBill();
                break;
            case 'W':
                $model = new EstateBill();
                break;
        }
        $number = $prefix . $type . $figure;
        while($model->uniqueness($number) || in_array($number, $hot_data)) {
            $number = $prefix . $type . rand(10000000, 99999999);
        }
        array_push($hot_data, $number);

        return $number;
    }

    /**
     * 获得电费单价
     * @return float
     */
    private function getElectricityUnit($admin_id) {
        $model = new ApartmentSettings();
        return $model->index2($admin_id)['electricity_fees'];
    }

    /**
     * 获得水费单价
     * @return float
     */
    private function getWaterUnit($admin_id) {
        $model = new ApartmentSettings();
        return $model->index2($admin_id)['water'];
    }

    /**
     * 获得气费单价
     * @return float
     */
    private function getGasUnit($admin_id) {
        $model = new ApartmentSettings();
        return $model->index2($admin_id)['gas_fee'];
    }

    /**
     * 获得网费单价
     * @return float
     */
    private function getNetUnit($admin_id) {
        $model = new ApartmentSettings();
        return $model->index2($admin_id)['net_fee'];
    }

    /**
     * 获得物业费单价
     * @return float
     */
    private function getEstateUnit($admin_id) {
        $model = new ApartmentSettings();
        return $model->index2($admin_id)['property_fee'];
    }

    /**
     * 编辑水电气网物业
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function EditBill() {
        $id = input()['id'];
        $type = input()['type'];// 1表示电费，2表示水费，3表示气费，4表示网费，5表示物业
        $status = input()['status'];// 1表示未缴，2表示已缴，3表示补缴
        $cost_method = input()['cost_method'];
        $time = input()['time'];// 时间戳

        switch ($type) {
            case 1:
                $model = new ElectricityBill();
                break;
            case 2:
                $model = new WaterBill();
                break;
            case 3:
                $model = new GasBill();
                break;
            case 4:
                $model = new NetBill();
                break;
            case 5:
                $model = new EstateBill();
                break;
        }

        $data['status'] = $status;
        $data['time'] = $time;
        $data['cost_method'] = $cost_method;
        $model->m_update($id, $data);

        returnJson(200,'成功')->send();die;
    }

    /**
     * 退租时需生成订单
     * @param $contract_id
     */
    public function generateOneBill($contract_id) {
//        $contract_id = input()['id'];
        $model = new ContracTmanagement();
        $list = $model->T_One($contract_id);
        foreach ($list['housing'] as $house) {
            $this->generateOneElectricityBill($house['h_id'], $house['h_type']);
            $this->generateOneWaterBill($house['h_id'], $house['h_type']);
            $this->generateOneGasBill($house['h_id'], $house['h_type']);
            $this->generateOneNetBill($house['h_id'], $house['h_type']);
            $this->generateOneEstateBill($house['h_id'], $house['h_type']);
        }
    }

    /**
     * 获取已缴未缴户数
     * @throws \think\Exception
     */
    public function getTodo() {
        $type = input()['type'];
        $admin_id = get_user_id(input()['token']);
        switch ($type) {
            case 1:
                $model = new ElectricityBill();
                break;
            case 2:
                $model = new WaterBill();
                break;
            case 3:
                $model = new GasBill();
                break;
            case 4:
                $model = new NetBill();
                break;
            case 5:
                $model = new EstateBill();
                break;
        }
        returnJson(200,'成功', $model->toDo($admin_id))->send();die;
    }

    /**
     * 生成指定房源电费账单
     * @param $house_id
     * @param $type
     */
    private function generateOneElectricityBill($house_id, $type) {
        $model = new ElectricityMeter();
        $notCount = $model->getNotCountHouse($house_id, $type);//获得未被统计过的抄表记录
        if (!empty($notCount)) {// 有记录且必须大于1，方可计算已使用量
            $house_info = [];
            // 制造每个房源账单信息
            foreach ($notCount as $house) {
                $room_number = $house['tung_num'] . '-' . $house['unit_num'] . '-' . $house['layer_num'] . '-' . $house['room_number'];
                if (!key_exists($room_number, $house_info)) {
                    $house_info[$room_number] = [];
                    $house_info[$room_number]['tenant_id'] = $house['tenant_id'];
                    $house_info[$room_number]['tenant_name'] = $house['tenant_name'];
                    $house_info[$room_number]['tenant_tel'] = $house['tenant_tel'];
                }
                // 账单基本信息
                $house_info[$room_number]['admin_id'] = $house['admin_id'];
                $house_info[$room_number]['number'] = $this->getNumber('D');
                $house_info[$room_number]['tung_num'] = $house['tung_num'];
                $house_info[$room_number]['unit_num'] = $house['unit_num'];
                $house_info[$room_number]['layer_num'] = $house['layer_num'];
                $house_info[$room_number]['room_number'] = $house['room_number'];
                $house_info[$room_number]['house_id'] = $house['house_id'];
                $house_info[$room_number]['type'] = $house['type'];

                // 统计最早时间和最晚时间、最早度数和最晚度数
                //首次将第一条记录作为其开始时间
                if (!isset($house_info[$room_number]['start_time'])) {
                    $a = $model->getLastRecord($house['house_id'], $house['type']);
                    if ($a === null) {
//                        $house_info[$room_number]['start_time'] = $house['time'];
//                        $house_info[$room_number]['start_number'] = $house['num'];
                        $house_info[$room_number]['start_time'] = 0;
                        $house_info[$room_number]['start_number'] = 0;
                    } else {
                        $house_info[$room_number]['start_time'] = $a['time'];
                        $house_info[$room_number]['start_number'] = $a['num'];
                    }
                }
                // 当前认为从数据库读出来的值越往后越新，故没有进行时间的判断
                $house_info[$room_number]['end_time'] = $house['time'];
                $house_info[$room_number]['end_number'] = $house['num'];

                // 统计费用
                $house_info[$room_number]['unit_price'] = $this->getElectricityUnit($house['admin_id']);//电费单价
                $house_info[$room_number]['time'] = '';
                $house_info[$room_number]['status'] = 1;

                // 账单基本信息
                $house_info[$room_number]['method'] = 1;
                $house_info[$room_number]['create_time'] = time();
            }

            // 计算总价
            foreach ($house_info as $k => &$item) {
                $item['usage'] = $item['end_number'] - $item['start_number'];
                $item['cost'] = upDecimal(bcmul($item['unit_price'] , $item['usage'], 6));
                if (empty($item['usage'])) {
                    unset($house_info[$k]);
                }
            }
            $house_info = array_merge_recursive($house_info);

            // 将每个房源账单信息插入账单表
            $model_bill = new ElectricityBill();
            foreach ($house_info as $h) {
                $model_bill->m_insert($h);
            }

            // 将抄表记录的统计状态更改为已统计
            $data['is_statistics'] = 1;
            foreach ($house_info as $house) {
                $a = $model->ListRoomNum($house['tung_num'], $house['unit_num'], $house['layer_num'], $house['room_number']);
                foreach ($a as $b) {
                    $model->m_update($b['id'], $data);
                }
            }
        }
    }

    /**
     * 生成指定房源水费账单
     * @param $house_id
     * @param $type
     */
    private function generateOneWaterBill($house_id, $type) {
        $model = new WaterMeter();
        $notCount = $model->getNotCountHouse($house_id, $type);//获得未被统计过的抄表记录
        if (!empty($notCount)) {// 有记录且必须大于1，方可计算已使用量
            $house_info = [];
            // 制造每个房源账单信息
            foreach ($notCount as $house) {
                $room_number = $house['tung_num'] . '-' . $house['unit_num'] . '-' . $house['layer_num'] . '-' . $house['room_number'];
                if (!key_exists($room_number, $house_info)) {
                    $house_info[$room_number] = [];
                    $house_info[$room_number]['tenant_id'] = $house['tenant_id'];
                    $house_info[$room_number]['tenant_name'] = $house['tenant_name'];
                    $house_info[$room_number]['tenant_tel'] = $house['tenant_tel'];
                }
                // 账单基本信息
                $house_info[$room_number]['admin_id'] = $house['admin_id'];
                $house_info[$room_number]['number'] = $this->getNumber('S');
                $house_info[$room_number]['tung_num'] = $house['tung_num'];
                $house_info[$room_number]['unit_num'] = $house['unit_num'];
                $house_info[$room_number]['layer_num'] = $house['layer_num'];
                $house_info[$room_number]['tenant_tel'] = $house['tenant_tel'];
                $house_info[$room_number]['house_id'] = $house['house_id'];
                $house_info[$room_number]['type'] = $house['type'];

                // 统计最早时间和最晚时间、最早度数和最晚度数
                //首次将第一条记录作为其开始时间
                if (!isset($house_info[$room_number]['start_time'])) {
                    $a = $model->getLastRecord($house['house_id'], $house['type']);
                    if ($a === null) {
//                        $house_info[$room_number]['start_time'] = $house['time'];
//                        $house_info[$room_number]['start_number'] = $house['num'];
                        $house_info[$room_number]['start_time'] = 0;
                        $house_info[$room_number]['start_number'] = 0;
                    } else {
                        $house_info[$room_number]['start_time'] = $a['time'];
                        $house_info[$room_number]['start_number'] = $a['num'];
                    }
                }
                // 当前认为从数据库读出来的值越往后越新，故没有进行时间的判断
                $house_info[$room_number]['end_time'] = $house['time'];
                $house_info[$room_number]['end_number'] = $house['num'];

                // 统计费用
                $house_info[$room_number]['unit_price'] = $this->getWaterUnit($house['admin_id']);//电费单价
                $house_info[$room_number]['time'] = '';
                $house_info[$room_number]['status'] = 1;

                // 账单基本信息
                $house_info[$room_number]['method'] = 1;
                $house_info[$room_number]['create_time'] = time();
            }

            // 计算总价
            foreach ($house_info as $k => &$item) {
                $item['usage'] = $item['end_number'] - $item['start_number'];
                $item['cost'] = upDecimal(bcmul($item['unit_price'] , $item['usage'], 6));
                if (empty($item['usage'])) {
                    unset($house_info[$k]);
                }
            }
            $house_info = array_merge_recursive($house_info);

            // 将每个房源账单信息插入账单表
            $model_bill = new WaterBill();
            foreach ($house_info as $h) {
                $model_bill->m_insert($h);
            }

            // 将抄表记录的统计状态更改为已统计
            $data['is_statistics'] = 1;
            foreach ($house_info as $house) {
                $a = $model->ListRoomNum($house['tung_num'], $house['unit_num'], $house['layer_num'], $house['room_number']);
                foreach ($a as $b) {
                    $model->m_update($b['id'], $data);
                }
            }
        }
    }

    /**
     * 生成指定房源气费账单
     * @param $house_id
     * @param $type
     */
    private function generateOneGasBill($house_id, $type) {
        $model = new GasMeter();
        $notCount = $model->getNotCountHouse($house_id, $type);//获得未被统计过的抄表记录
        if (!empty($notCount)) {// 有记录且必须大于1，方可计算已使用量
            $house_info = [];
            // 制造每个房源账单信息
            foreach ($notCount as $house) {
                $room_number = $house['tung_num'] . '-' . $house['unit_num'] . '-' . $house['layer_num'] . '-' . $house['room_number'];
                if (!key_exists($room_number, $house_info)) {
                    $house_info[$room_number] = [];
                    $house_info[$room_number]['tenant_id'] = $house['tenant_id'];
                    $house_info[$room_number]['tenant_name'] = $house['tenant_name'];
                    $house_info[$room_number]['tenant_tel'] = $house['tenant_tel'];
                }
                // 账单基本信息
                $house_info[$room_number]['admin_id'] = $house['admin_id'];
                $house_info[$room_number]['number'] = $this->getNumber('Q');
                $house_info[$room_number]['tung_num'] = $house['tung_num'];
                $house_info[$room_number]['unit_num'] = $house['unit_num'];
                $house_info[$room_number]['layer_num'] = $house['layer_num'];
                $house_info[$room_number]['room_number'] = $house['room_number'];
                $house_info[$room_number]['house_id'] = $house['house_id'];
                $house_info[$room_number]['type'] = $house['type'];

                // 统计最早时间和最晚时间、最早度数和最晚度数
                //首次将第一条记录作为其开始时间
                if (!isset($house_info[$room_number]['start_time'])) {
                    $a = $model->getLastRecord($house['house_id'], $house['type']);
                    if ($a === null) {
//                        $house_info[$room_number]['start_time'] = $house['time'];
//                        $house_info[$room_number]['start_number'] = $house['num'];
                        $house_info[$room_number]['start_time'] = 0;
                        $house_info[$room_number]['start_number'] = 0;
                    } else {
                        $house_info[$room_number]['start_time'] = $a['time'];
                        $house_info[$room_number]['start_number'] = $a['num'];
                    }
                }
                // 当前认为从数据库读出来的值越往后越新，故没有进行时间的判断
                $house_info[$room_number]['end_time'] = $house['time'];
                $house_info[$room_number]['end_number'] = $house['num'];

                // 统计费用
                $house_info[$room_number]['unit_price'] = $this->getGasUnit($house['admin_id']);//电费单价
                $house_info[$room_number]['time'] = '';
                $house_info[$room_number]['status'] = 1;

                // 账单基本信息
                $house_info[$room_number]['method'] = 1;
                $house_info[$room_number]['create_time'] = time();
            }

            // 计算总价
            foreach ($house_info as $k => &$item) {
                $item['usage'] = $item['end_number'] - $item['start_number'];
                $item['cost'] = upDecimal(bcmul($item['unit_price'] , $item['usage'], 6));
                if (empty($item['usage'])) {
                    unset($house_info[$k]);
                }
            }
            $house_info = array_merge_recursive($house_info);

            // 将每个房源账单信息插入账单表
            $model_bill = new GasBill();
            foreach ($house_info as $h) {
                $model_bill->m_insert($h);
            }

            // 将抄表记录的统计状态更改为已统计
            $data['is_statistics'] = 1;
            foreach ($house_info as $house) {
                $a = $model->ListRoomNum($house['tung_num'], $house['unit_num'], $house['layer_num'], $house['room_number']);
                foreach ($a as $b) {
                    $model->m_update($b['id'], $data);
                }
            }
        }
    }

    /**
     * 生成指定房源网费账单
     * @param $house_id
     * @param $type
     */
    private function generateOneNetBill($house_id, $type) {
        if ($type == 1) {
            $model = new HousingInformation();
        } else {
            $model = new Shops();
        }
        $model_contract = new ContracTmanagement();
        $data = [];

        if ($type == 1) {
            $house = $model->detail($house_id);
            $data['admin_id'] = $house['create_id'];
            $data['tung_num'] = $house['h_tung_num'];
            $data['unit_num'] = $house['h_unit_num'];
            $data['layer_num'] = $house['h_layer_num'];
            $data['room_number'] = $house['h_room_number'];
            $data['house_id'] = $house['housing_id'];
            $data['type'] = 1;
            $data['number'] = $this->getNumber('N');
            $data['create_time'] = time();
            $data['method'] = 1;
            $data['status'] = 1;

            $detail = $model_contract->contratHouse($house['housing_id'], 1);
            $contract_id = $detail['c_c_mid'];

            $detail = $model_contract->ContractTenantInfo($contract_id);
            $data['tenant_id'] = $detail['tenant_id'];
            $data['tenant_name'] = $detail['tenant_name'];
            $data['tenant_tel'] = $detail['tenant_tel'];

            $detail = $model_contract->detail($contract_id);
            if (strtotime('-1 month') < $detail['c_a_time']) {// 签订合同时间不足一个月，起始时间用起实际时间
                $data['start_time'] = $detail['c_a_time'];
                $data['end_time'] = time();
                $data['usage'] = 1;//不满一月按一月计算
            } else {
                $data['start_time'] = strtotime('-1 month');
                $data['end_time'] = time();
                $data['usage'] = 1;
            }

            $data['unit_price'] = $this->getNetUnit($house['create_id']);//网费单价
            $data['cost'] = upDecimal(bcmul($data['unit_price'] , $data['usage'], 6));
            $model_bill = new NetBill();
            $model_bill->m_insert($data);
        } else {
            $shop = $model->detail($house_id);
            $data['admin_id'] = $shop['create_id'];
            $data['tung_num'] = $shop['s_tung_num'];
            $data['unit_num'] = $shop['s_unit_num'];
            $data['layer_num'] = $shop['s_layer_num'];
            $data['room_number'] = $shop['s_room_number'];
            $data['house_id'] = $shop['shops_id'];
            $data['type'] = 2;
            $data['number'] = $this->getNumber('N');
            $data['create_time'] = time();
            $data['method'] = 1;
            $data['status'] = 1;

            $detail = $model_contract->contratHouse($shop['shops_id'], 2);
            $contract_id = $detail['c_c_mid'];

            $detail = $model_contract->ContractTenantInfo($contract_id);
            $data['tenant_id'] = $detail['tenant_id'];
            $data['tenant_name'] = $detail['tenant_name'];
            $data['tenant_tel'] = $detail['tenant_tel'];

            $detail = $model_contract->detail($contract_id);
            if (strtotime('-1 month') < $detail['c_a_time']) {// 签订合同时间不足一个月，起始时间用起实际时间
                $data['start_time'] = $detail['c_a_time'];
                $data['end_time'] = time();
                $data['usage'] = 1;
            } else {
                $data['start_time'] = strtotime('-1 month');
                $data['end_time'] = time();
                $data['usage'] = 1;
            }

            $data['unit_price'] = $this->getNetUnit($shop['create_id']);//电费单价
            $data['cost'] = upDecimal(bcmul($data['unit_price'] , $data['usage'], 6));

            $model_bill = new NetBill();
            $model_bill->m_insert($data);
        }
    }

    /**
     * 生成指定房源电费账单
     * @param $house_id
     * @param $type
     */
    private function generateOneEstateBill($house_id, $type) {
        if ($type == 1) {
            $model = new HousingInformation();
        } else {
            $model = new Shops();
        }
        $model_contract = new ContracTmanagement();
        $data = [];

        if ($type == 1) {
            $house = $model->detail($house_id);
            $data['admin_id'] = $house['create_id'];
            $data['tung_num'] = $house['h_tung_num'];
            $data['unit_num'] = $house['h_unit_num'];
            $data['layer_num'] = $house['h_layer_num'];
            $data['room_number'] = $house['h_room_number'];
            $data['area'] = $house['h_area'];
            $data['house_id'] = $house['housing_id'];
            $data['type'] = 1;
            $data['number'] = $this->getNumber('W');
            $data['create_time'] = time();
            $data['method'] = 1;
            $data['status'] = 1;

            $detail = $model_contract->contratHouse($house['housing_id'], 1);
            $contract_id = $detail['c_c_mid'];

            $detail = $model_contract->ContractTenantInfo($contract_id);
            $data['tenant_id'] = $detail['tenant_id'];
            $data['tenant_name'] = $detail['tenant_name'];
            $data['tenant_tel'] = $detail['tenant_tel'];

            $detail = $model_contract->detail($contract_id);
            if (strtotime('-1 month') < $detail['c_a_time']) {// 签订合同时间不足一个月
                $data['start_time'] = $detail['c_a_time'];
                $data['end_time'] = time();
                $data['usage'] = 1;
            } else {
                $data['start_time'] = strtotime('-1 month');
                $data['end_time'] = time();
                $data['usage'] = 1;
            }

            $data['unit_price'] = $this->getEstateUnit($house['create_id']);//电费单价
            $data['cost'] = upDecimal(bcmul(bcmul($data['unit_price'] , $data['usage'], 6) , $data['area'], 6));

            $model_bill = new EstateBill();
            $model_bill->m_insert($data);
        } else {
            $shop = $model->detail($house_id);
            $data['admin_id'] = $shop['create_id'];
            $data['tung_num'] = $shop['s_tung_num'];
            $data['unit_num'] = $shop['s_unit_num'];
            $data['layer_num'] = $shop['s_layer_num'];
            $data['room_number'] = $shop['s_room_number'];
            $data['area'] = $shop['s_area'];
            $data['house_id'] = $shop['shops_id'];
            $data['type'] = 2;
            $data['number'] = $this->getNumber('W');
            $data['create_time'] = time();
            $data['method'] = 1;
            $data['status'] = 1;

            $detail = $model_contract->contratHouse($shop['shops_id'], 2);
            $contract_id = $detail['c_c_mid'];

            $detail = $model_contract->ContractTenantInfo($contract_id);
            $data['tenant_id'] = $detail['tenant_id'];
            $data['tenant_name'] = $detail['tenant_name'];
            $data['tenant_tel'] = $detail['tenant_tel'];

            $detail = $model_contract->detail($contract_id);
            if (strtotime('-1 month') < $detail['c_a_time']) {// 签订合同时间不足一个月
                $data['start_time'] = $detail['c_a_time'];
                $data['end_time'] = time();
                $data['usage'] = 1;
            } else {
                $data['start_time'] = strtotime('-1 month');
                $data['end_time'] = time();
                $data['usage'] = 1;
            }

            $data['unit_price'] = $this->getEstateUnit($shop['create_id']);//电费单价
            $data['cost'] = upDecimal(bcmul(bcmul($data['unit_price'] , $data['usage'], 6) , $data['area'], 6));

            $model_bill = new EstateBill();
            $model_bill->m_insert($data);
        }
    }
}